import React from 'react';
import _ from 'lodash';
import { findDOMNode } from 'react-dom';
import { Tag } from 'antd';
import { DragSource, DropTarget } from 'react-dnd';
import { ItemTypes } from './constants';



const source = {
  beginDrag(props) {
    return {
      id: props.id,
      index: props.index,
    };
  }
};

const target = {
  hover: (props, monitor, component) => {
    if (!component) {
      return;
    }
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;

    if (dragIndex === hoverIndex) {
      return;
    }

    const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();
    const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
    const clientOffset = monitor.getClientOffset();
    const hoverClientY = clientOffset.y - hoverBoundingRect.top;
    if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
      return;
    }
    if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
      return;
    }

    props.moveTag(dragIndex, hoverIndex);

    monitor.getItem().index = hoverIndex;
  }
};


class TagItem extends React.Component {


  render() {

    const { id, text, isDragging, connectDragSource, connectDropTarget } = this.props;
    const opacity = isDragging ? 0 : 1;

    return (
      connectDragSource &&
      connectDropTarget &&
      connectDragSource(
        connectDropTarget(
          <div style={{ opacity, float: 'left' }}>
            <Tag
              closable={true}
              color={'orange'}
              onClose={() => { console.warn('当前标签ID： ', id) }}
            >
              {text}
            </Tag>
          </div>
        )
      )
    );
  }
};

export default _.flow(
  DragSource(
    ItemTypes.TAG,
    source,
    (connect, monitor) => ({
      connectDragSource: connect.dragSource(),
      isDragging: monitor.isDragging(),
    }),
  ),
  DropTarget(
    ItemTypes.TAG,
    target,
    (connect) => ({
      connectDropTarget: connect.dropTarget(),
    }),
  ),
)(TagItem);